package com.gao.security.autoconfig.verificationcode.handler;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.gao.security.verificationcode.common.BaseVo;
import com.gao.security.verificationcode.common.ResponseCode;
import com.gao.security.verificationcode.exception.ValidateCodeIncorrectException;
import com.gao.security.verificationcode.exception.ValidateCodeNotFoundException;
import com.gao.security.verificationcode.exception.ValidateCodeTimeoutException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author GaoShuangWen
 * @date 2018-12-11 20:58
 */
@Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter printWriter = response.getWriter();
        printWriter.append(
                objectMapper.writeValueAsString(getInfoByAuthenticationException(exception)));
    }

    protected BaseVo getInfoByAuthenticationException(AuthenticationException exception) {
        if (exception instanceof BadCredentialsException) {
            return BaseVo.failure(ResponseCode.USER_LOGIN_ERROR);
        }
        if (exception instanceof UsernameNotFoundException) {
            return BaseVo.failure(ResponseCode.USER_NOT_EXIST);
        }
        if (exception instanceof ValidateCodeTimeoutException) {
            return BaseVo.failure(ResponseCode.VALIDATECODE_TIME_OUT);
        }
        if (exception instanceof ValidateCodeIncorrectException
                ||exception instanceof ValidateCodeNotFoundException) {
            return BaseVo.failure(ResponseCode.VALIDATECODE_FAILURE);
        }
        return BaseVo.failure(ResponseCode.PERMISSION_NO_ACCESS);
    }

}